package com.zq.qq2.service;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.zq.qq2.Constant;
import com.zq.qq2.FileUtils;
import com.zq.qq2.MediaUtil;
import com.zq.qq2.R;
import com.zq.qq2.thread.Login;
import com.zq.qq2.thread.Startup;

import org.json.JSONObject;

import java.io.File;
import java.io.FilenameFilter;

/**
 *
 *
 */
public class FloatQQService extends Service {
    //定义浮动窗口布局
    LinearLayout mFloatLayout;
    WindowManager.LayoutParams wmParams;
    //创建浮动窗口设置布局参数的对象
    WindowManager mWindowManager;

    Button mRun;

    Vibrator vibrator;
    void deleteDeviceId() {
        new Thread(){
            @Override
            public void run() {
                // 删除串号
                File[] data = new File("/mnt/sdcard/zhangqing/data/").listFiles();
                for (int i =  0; i < data.length; i ++ ) {
                    File fd = data[i];
                    if (!fd.isDirectory())
                        continue;
                    Log.v("xuebiao_file", fd.getAbsolutePath());
                    final JSONObject json = FileUtils.GetJson(FileUtils.read("/data/local/db.json"));
                    File[] files = fd.listFiles(new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String filename) {
                            return filename.endsWith(FileUtils.GetString(json, "phone_deviceid") + ".txt");
                        }
                    });
                    for (File f : files) {
                        Log.v("xuebiao_file_2", f.getAbsolutePath());
                        String tmp = FileUtils.read(f.getAbsolutePath());
                        if ( !tmp.equals("") ) {
                            FileUtils.write("/mnt/sdcard/zhangqing/shanchu/" + f.getName(), tmp);
                        }
                        f.delete();
                    }
                }
            }
        }.start();
    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch ( msg.what ) {
                case 0:
                    QQAccount = "";
                    QQPasswd = "";
                    new Startup(FloatQQService.this, handler).start();
                    break;
                case 1:
                    new Login(FloatQQService.this, handler).start();
                    break;
                case 4:

                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(), "\n完成数据操作\n", Toast.LENGTH_SHORT).show();
                            MediaUtil.Notify(getApplicationContext(), R.raw.loginsuccess);
                        }
                    });
                    new Thread(){
                        @Override
                        public void run() {
                            File fs = new File("/mnt/sdcard/zhangqing/data/");
                            if ( fs.exists() ) {
                                File[] data = new File("/mnt/sdcard/zhangqing/data/").listFiles();
                                for (int i =  0; i < data.length; i ++ ) {
                                    File fd = data[i];
                                    if ( !fd.isDirectory() )
                                        continue;
                                    File[] files = fd.listFiles(new FilenameFilter() {
                                        @Override
                                        public boolean accept(File dir, String filename) {
                                            return filename.endsWith(Constant.getDeviceId(FloatQQService.this) + ".txt");
                                        }
                                    });
                                    for (File f : files) {
                                        try {
                                            String content = FileUtils.read(f.getAbsolutePath());
                                            JSONObject jsonObject = new JSONObject(content);
                                            String qq = jsonObject.getString("QQ");
                                            if ( !TextUtils.isEmpty(qq) ) {
                                                continue;
                                            }
                                            jsonObject.put("QQ", QQAccount);
                                            jsonObject.put("QQPwd", QQPasswd);
                                            FileUtils.write(f.getAbsolutePath(), jsonObject.toString());
                                            Constant.Debug("更新数据文件:" + f.getAbsolutePath());
                                        } catch (Exception e) {

                                        }
                                    }
                                }
                            }
                        }
                    }.start();
                    break;
                case 10:
                    MediaUtil.Vibrater(FloatQQService.this, R.raw.qqaccountfail, 5);
                    builder = new AlertDialog.Builder(FloatQQService.this);
                    builder.setMessage(msg.obj.toString());
                    ad = builder.create();
                    ad.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                    ad.show();
                    deleteDeviceId();
                    break;
                case 6:
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(FloatQQService.this, "多次登录失败,请手动干预", Toast.LENGTH_LONG).show();
                        }
                    });
                    deleteDeviceId();
                    break;
                default:
                    break;

            }
        }
    };

    AlertDialog.Builder builder = null;
    AlertDialog ad = null;

    public static String QQAccount = "";
    public static String QQPasswd  = "";
    boolean destroy = false;
    @Override
    public void onCreate() {
        super.onCreate();
        if (!Constant.getSP(this).getBoolean("qqshow", true)) {
            this.stopSelf();
            return;
        }
        createFloatView();
        moveObject();
        try {
            new File("/mnt/sdcard/zhangqing/qq").mkdir();
            new File("/mnt/sdcard/zhangqing/src").mkdir();
            new File("/mnt/sdcard/zhangqing/shanchu").mkdir();
            new File("/mnt/sdcard/zhangqing/src/qq.txt").createNewFile();
            new File("/mnt/sdcard/zhangqing/src/qqerr.txt").createNewFile();
            new File("/mnt/sdcard/zhangqing/src/qqnet.txt").createNewFile();
        } catch (Exception e) {
        }
        vibrator = (Vibrator) getApplication().getSystemService(Service.VIBRATOR_SERVICE);
        mRun.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Constant.getSP(FloatQQService.this).getBoolean("move", false))
                    return;
                handler.sendEmptyMessage(0);
            }
        });
    }
    private void moveObject() {
        mRun.setOnTouchListener( new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                move(event);
                return false;
            }
        });
        mFloatLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                move(event);
                return false;
            }
        });
    }
    private void move(MotionEvent event) {
        if ( !Constant.getSP(FloatQQService.this).getBoolean("move", false) )
            return;
        if( event.getAction() == MotionEvent.ACTION_MOVE ) {
            wmParams.x = (int) event.getRawX() - 90;
            wmParams.y = (int) event.getRawY() - 60;
            mWindowManager.updateViewLayout(mFloatLayout, wmParams);
            Constant.getSP(this).edit().putInt("qqX", wmParams.x).putInt("qqY", wmParams.y).commit();
        }
    }
    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Intent notificationIntent = new Intent();
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        Notification noti = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
            noti = new Notification.Builder(this)
                    .setContentTitle("QQ登录程序")
                    .setContentText("防止杀死")
                    .setSmallIcon(R.drawable.ic_launcher)
                    .setContentIntent(pendingIntent)
                    .build();
        }
        startForeground(12346, noti);
        return Service.START_STICKY;
    }

    private void createFloatView() {

        wmParams = new WindowManager.LayoutParams();
        mWindowManager = (WindowManager)getApplication().getSystemService(getApplication().WINDOW_SERVICE);
        wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        //设置图片格式，效果为背景透明
        wmParams.format = PixelFormat.RGBA_8888;
        //设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        //调整悬浮窗显示的停靠位置为左侧置顶
        wmParams.gravity = Gravity.TOP | Gravity.LEFT;
        // 以屏幕左上角为原点，设置x、y初始值，相对于gravity

        int x = Constant.getSP(this).getInt("qqX", 0);
        int y = Constant.getSP(this).getInt("qqY", 100);
        wmParams.x = x;
        wmParams.y = y;


        // 设置悬浮窗口长宽数据

        wmParams.width = 240;
        wmParams.height = 120;

        LayoutInflater inflater = LayoutInflater.from(getApplication());
        //获取浮动窗口视图所在布局
        mFloatLayout = (LinearLayout) inflater.inflate(R.layout.float_qq, null);
        //添加mFloatLayout
        mWindowManager.addView(mFloatLayout, wmParams);
        //浮动窗口按钮
        mRun = (Button)mFloatLayout.findViewById(R.id.float_id);

        mRun.setText("QQ");

        mFloatLayout.measure(View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
                .makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        if(mFloatLayout != null) {
            mWindowManager.removeView(mFloatLayout);
        }
        destroy = true;
    }
}
